'''
Created on 30/04/2012

@author: Bruna, Bruno
'''

BAUDRATE = 9600

from sample_analyser import SampleAnalyser
import serial
import sys

def measure(port, num_measurements):
    samples = []
    for i in xrange(num_measurements):
        port.write('M')
        m = port.readline()
        m = m.rstrip('\r\n').split(',')
        samples.append( (int(m[0]),int(m[1]),int(m[2])) )
    return samples    

def calibrate(port):
    print "Hold up a white object in front of the sensor, then press any key to calibrate...\n"
    raw_input()
    port.write('C')
    print "Capacitors values:", port.readline()
    print "Integration values:", port.readline()
    measure(port)
    print "All values should be under 1000. If they're not, try calibrating again, or decreasing the ambient brightness somehow."
    print "Press \"C\" to calibrate again"
    
def assert_color(probabilities):
    max_prob, max_color = -1.0, None
    
    for color, probability in probabilities.items():
        if (probability >= max_prob):
            max_prob = probability
            max_color = color
    return max_prob, max_color

if __name__ == "__main__":
    num_measurements = 10
    try:
        index = sys.argv.index('-m')
        if (index > -1):
            num_measurements = int(sys.argv[index + 1])
    except ValueError:
        pass
        
    port_name = "COM3"
    try:
        index = sys.argv.index('-p')
        if (index > -1):
            port_name = sys.argv[index + 1]
    except ValueError:
        pass
        
    files = ["Red.csv", "Green.csv", "Blue.csv", "Orange.csv", "Yellow.csv", "Lilac.csv", "LightBlue.csv"]
        
    sample_analyser = SampleAnalyser(files)

    port = serial.Serial(port_name, BAUDRATE)
    print "Connection opened."
   
    # Handshake
    port.write('A')
    print "Handshake completed"
    
    while True:
        cmd = raw_input()
        
        if (cmd == 'X'):
            break
        elif (cmd == 'D' or cmd == 'L'):
            port.write(cmd)
            continue
        elif (cmd == 'C'):
            calibrate(port)
        elif (cmd == 'M'):
            samples = measure(port, num_measurements)
            probabilities = sample_analyser.analyse_samples(samples)
            max_prob, max_color = assert_color(probabilities)
            print max_color, max_prob
        elif (cmd == 'I'):
            port.write('I')
            print "Capacitors values:", port.readline()
            print "Integration values:", port.readline()
        
    port.close()